package com.jpragma.logviewer.actions {
	import com.jpragma.logviewer.events.LogManagementEvent;
	import com.jpragma.logviewer.events.LogViewerEvent;
	import com.jpragma.logviewer.model.AppSettings;
	import com.jpragma.logviewer.model.LogMessages;
	
	import flash.net.LocalConnection;
	
	import org.spicefactory.parsley.mvc.FrontController;
	
	public class LocalConnectionLogMessageAction implements LogMessageAction {
		private var _connectionName:String = "_loggerConnection";
		private var _settings:AppSettings;
		private var _logMessages:LogMessages;
		
		private var connection:LocalConnection;
		
		public function LocalConnectionLogMessageAction() {
		}

		public function set connectionName (value:String) : void {
			_connectionName = value;
		}
		
		/**
		 * The name of LocalConnection object, receiver must use the same name. The default is _loggerConnection.
		 */
		public function get connectionName () : String {
			return _connectionName;
		}
		
		public function set settings(settings:AppSettings):void {
			_settings = settings;
		}
		
		public function set logMessages(messages:LogMessages):void {
			_logMessages = messages;
		}

		public function startAccepting():void {
			connection = new LocalConnection();
			connection.client = this;
			connection.allowDomain("*");
			connection.allowInsecureDomain("*");
			connection.connect(_connectionName);
		}
		
		public function stopAccepting():void {
			if (connection != null) {
				connection.close();
				connection = null;
			}
		}
		
		public function onAcceptingChange(event:LogManagementEvent):void {
			if (event.name == LogManagementEvent.START_ACCEPTING) {
				startAccepting();
			} else if (event.name == LogManagementEvent.STOP_ACCEPTING){
				stopAccepting();
			}
		}
		
		public function onCleanMessages(event:LogManagementEvent):void {
			_logMessages.removeAll();
		}
		
		public function logMessage(message:Object):void {
			// purge old messages
			while (_logMessages.length > _settings.maxNumberOfMessages) {
				_logMessages.removeItemAt(0);
			}
			
			_logMessages.addItem(message);
			var event:LogViewerEvent = new LogViewerEvent(LogViewerEvent.LOG_MESSAGE_ADDED);
			FrontController.root.dispatchEvent(event);
		}
		
	}
}